//
//  DBNetWork.m
//  KidReading
//
//  Created by telen on 15/7/21.
//  Copyright (c) 2015年 刘赞黄Telen. All rights reserved.
//

#import "DBNetWork.h"
#import "ConstDefine.h"

//Debug Login uid and token
//#define __uid 7  //id
//#define __token  @"d6f1f8684d4e3df9760493df67abc656" //token
#define __caid 86 //yizhangtong
#define __catoken @"ec325bd11ac38bc393b7b644b84f5378"

@implementation DBHelper (DBNetWork)

#pragma mark- AFN

- (void)askNet:(NSString*)port andBaseUrl:(NSString*)baseUrl parameters:(NSDictionary*)dict success:(void (^)(NSDictionary* retDict))success failure:(void (^)(NSError *error))failure;
{
    [[NetRequest shareSingle] askNet:port andBaseUrl:baseUrl parameters:dict success:success failure:failure];
}

- (void)askSer_Net:(NSString*)port parameters:(NSDictionary*)dict_ref success:(void (^)(NSDictionary* retDict))success failure:(void (^)(NSError *error))failure
{
    if (![self isUserTimeOK]) {
        [[WaitingShow shareSingleShow] showString:NSLocalizedString(@"timeError", nil) andAutoHide:YES];
        [[RootViewController shareLastInstance] load_UserInfo_Server_Login:nil];
        failure(nil);
    }
    //
    [self askNet:port andBaseUrl:__Ser3_0_URL_Base_ parameters:dict_ref success:^(NSDictionary *retDict) {
#if __Debug_Net_Error
        NSLog(@"debugMessage: %@  <<<  %@",retDict[@"debugMessage"],port);
#endif
#if __Debug_Net
        NSLog(@"%@",port);
        NSLog(@"Debug_Ser2 -->>> %@",retDict);
#endif
        NSDictionary* dict = retDict[@"retinfo"];
        NSString* msg = retDict[@"msg"];
        NSInteger flag = [retDict[@"flag"] integerValue];
        if (msg) {
            [[WaitingShow shareSingleShow] showString:msg andAutoHide:YES];
            if (flag == 1001) {//token 过期
                NSLog(@"token out: /telen%@",port);
                [[DBHelper shareInstance] showTokenOutMsg:msg];
                return ;
            }
        }
        if (flag == 1) {
            if (dict.count == 0) {
                dict = @{@"flag":@(1)};
            }
            success(dict);
        }else{
            success(@{});
        }
    } failure:failure];
}

- (void)askSer_DB_Net:(NSString*)port parameters:(NSDictionary*)dict_ref success:(void (^)(NSDictionary* retDict))success failure:(void (^)(NSError *error))failure
{
    [self askSer_Net:port parameters:dict_ref success:^(NSDictionary *rDict) {
        if(success)success(rDict);
    } failure:failure];
}

//
- (NSInteger)uid_TABLE_TIMESTAMP_forTable:(NSString*)tableName uid:(NSInteger)uid
{
    if ([tableName isEqualToString:[TABLE_NOTICE tableName]]) {
        return uid;
    }
    return -1;
}
//
- (void)update_TABLE_TIMESTAMP_forTable:(NSString*)tableName uid:(NSInteger)uid timestamp:(NSString*)time
{
    uid = [self uid_TABLE_TIMESTAMP_forTable:tableName uid:uid];
    //
    long long stm = [time longLongValue];
    NSString* tableClass = NSStringFromClass([TABLE_TIMESTAMP class]);
    [self readerDB_getList:^(NSArray *list) {
        TABLE_TIMESTAMP* tb_timestame = [list firstObject];
        if (nil == tb_timestame) {
            tb_timestame = [TABLE_TIMESTAMP instance];
            tb_timestame.userId = uid;
        }
        if (tb_timestame && [tb_timestame hasProperty:tableName]) {
            [tb_timestame setValue:@(stm) forKey:tableName];
            [self readerDB_updateListToTableClass:tableClass dictArr:@[[tb_timestame properties_value]] complete:nil];
        }else{
            NSLog(@"%@没有column: %@ __update",tableClass,tableName);
        }
    } fromTableClass:tableClass where:[NSString stringWithFormat:@" where userId=%@",@(uid)]];
    //
    //更新最后时间
    [DataProcessing do_Async_quick:^{
        [self.dbQue inTransaction:^(JRFMDatabase *db, BOOL *rollback) {
            [self update_TABLE_TIMESTAMP_LAST_timestamp:time db:db];
        }];
    }];
    //
}
- (void)update_TABLE_TIMESTAMP_forTable:(NSString*)tableName uid:(NSInteger)uid timestamp:(NSString*)time db:(JRFMDatabase *)db
{
    uid = [self uid_TABLE_TIMESTAMP_forTable:tableName uid:uid];
    //
    long long stm = [time longLongValue];
    NSString* tableClass = NSStringFromClass([TABLE_TIMESTAMP class]);
    NSArray *list = [self getList_fromTableClass:tableClass where:[NSString stringWithFormat:@" where userId=%@",@(uid)] db:db];
    TABLE_TIMESTAMP* tb_timestame = [list firstObject];
    if (nil == tb_timestame) {
        tb_timestame = [TABLE_TIMESTAMP instance];
        tb_timestame.userId = uid;
    }
    if (tb_timestame && [tb_timestame hasProperty:tableName]) {
        [tb_timestame setValue:@(stm) forKey:tableName];
        [self updateListToTableClass:tableClass dictArr:@[[tb_timestame properties_value]] db:db];
    }else{
        NSLog(@"%@没有column: %@ __update",tableClass,tableName);
    }
    //更新最后时间
    [self update_TABLE_TIMESTAMP_LAST_timestamp:time db:db];
    //
}

- (void)update_TABLE_TIMESTAMP_LAST_timestamp:(NSString*)time db:(JRFMDatabase *)db
{
    NSString* name = @"lasttime";
    long long stm = [time longLongValue];
    NSString* tableClass = NSStringFromClass([TABLE_TIMESTAMP_LAST class]);
    NSArray *list = [self getList_fromTableClass:tableClass where:[NSString stringWithFormat:@" where name=%@",name] db:db];
    TABLE_TIMESTAMP_LAST* tb_timelast= [list firstObject];
    if (nil == tb_timelast) {
        tb_timelast = [TABLE_TIMESTAMP_LAST instance];
        tb_timelast.name = name;
    }
    if (tb_timelast) {
        self.tb_lastTime = tb_timelast;
        if (tb_timelast.time >= stm) {
            return;
        }
        [tb_timelast setValue:@(stm) forKey:@"time"];
        [self updateListToTableClass:tableClass dictArr:@[[tb_timelast properties_value]] db:db];
    }
}

- (BOOL)isUserTimeOK
{
    if (self.tb_lastTime) {
        LongLong time = self.tb_lastTime.time;
        NSTimeInterval tt = (NSTimeInterval)time;
        NSTimeInterval td = [NSDate date].timeIntervalSince1970*1000;
        if (tt > td + __TimeStampInterval*60*1000) {
            return NO;
        }
    }
    return YES;
}

//5分钟时间戳，过时控制判断
- (void)isTimestampOut_TABLE_TIMESTAMP_forTable:(NSString*)tableName complete:(void(^)(BOOL,NSTimeInterval))isout
{
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    [self isTimestampOut_TABLE_TIMESTAMP_forTable:tableName uid:(NSInteger)uinfo.uid complete:isout];
}
- (void)isTimestampOut_TABLE_TIMESTAMP_forTable:(NSString*)tableName uid:(NSInteger)uid complete:(void(^)(BOOL,NSTimeInterval))isout
{
    uid = [self uid_TABLE_TIMESTAMP_forTable:tableName uid:uid];
    //
    NSString* tableClass = NSStringFromClass([TABLE_TIMESTAMP class]);
    [self readerDB_getList:^(NSArray *list) {
        TABLE_TIMESTAMP* tb_timestame = [list firstObject];
        if (nil == tb_timestame) {
            tb_timestame = [TABLE_TIMESTAMP instance];
        }
        if (tb_timestame && [tb_timestame hasProperty:tableName]) {
            LongLong time = [[tb_timestame valueForKey:tableName] longLongValue];
            NSTimeInterval tt = (NSTimeInterval)time;
            if (self.isLimitedTimeForNet == NO) {
                isout(YES,tt);
            }else{
                NSTimeInterval td = [NSDate date].timeIntervalSince1970*1000;
                if (fabsl(tt-td) < __TimeStampInterval*60*1000) {
                    isout(NO,tt);
                }else{
                    isout(YES,tt);
                }
            }
        }else{
            NSLog(@"%@没有column: %@ __is",tableClass,tableName);
            isout(YES,0);
        }
    } fromTableClass:tableClass where:[NSString stringWithFormat:@" where userId=%@",@(uid)]];
}



- (NSString*)getUMSuiid
{
    NSString* udid = [WY3SDKLogin get_idfv];
    if ([udid hasPrefix:@"idfv_"]) {
        return udid;
    }else {
        return [NSString stringWithFormat:@"idfv_%@",udid];
    }
}





#pragma mark-ReadingCount
- (void)getNetReadingCount_complete:(void (^)(NSDictionary *))comp noSelect:(BOOL)noSelect
{
    NSString* table = [TABLE_READING_COUNT tableName];
    NSString* tableClass = NSStringFromClass([TABLE_READING_COUNT class]);
    //
    [self todoForTableName:table tableClass:tableClass netPort:__Ser3_GetReadingCount ref:nil willDB:nil complete:^{
        if(noSelect){
            if(comp)comp(@{});
        }else{
            [self selectReadingCountList:^(NSDictionary *dict) {
                if(comp)comp(dict);
            }];
        }
    }];
}

#pragma mark-Book
- (void)getNetBook_complete:(void (^)(void))comp
{
    NSString* table = [TABLE_BOOKS tableName];
    NSString* tableClass = NSStringFromClass([TABLE_BOOKS class]);
    //
    [self todoForTableName:table tableClass:tableClass netPort:__Ser3_GetBookList_All ref:nil willDB:^(NSDictionary *retDict) {
        //Spotlight 系统搜索，删改
        if (!self.isSpotlightClear && ![DataProcessing iOS9_low]) {
            [DataProcessing do_Async_quick:^{
                NSArray* dictList = retDict[@"delete"];
                NSMutableArray *itemsToIndex = [NSMutableArray array];
                for (NSDictionary* dic in dictList) {
                    TABLE_BOOKS* obj = (TABLE_BOOKS*)[NSClassFromString(tableClass) JRMJ_objectWithKeyValues:dic];
                    [itemsToIndex addObject:[NSString stringWithFormat:@"%@",@(obj.bookId)]];
                }
                if(itemsToIndex.count > 0)[[CSSearchableIndex defaultSearchableIndex] deleteSearchableItemsWithIdentifiers:itemsToIndex
                                                                                                         completionHandler:nil];//删
                //
                dictList = retDict[@"update"];
                itemsToIndex = [NSMutableArray array];
                for (NSDictionary* dic in dictList) {
                    TABLE_BOOKS* obj = (TABLE_BOOKS*)[NSClassFromString(tableClass) JRMJ_objectWithKeyValues:dic];
                    CSSearchableItemAttributeSet *attributeSet = [[CSSearchableItemAttributeSet alloc] initWithItemContentType:(NSString*)kUTTypeJSON];
                    attributeSet.title = obj.name_zh;
                    attributeSet.contentDescription = [NSString stringWithFormat:@"%@/%@\n【让孩子爱上阅读】",obj.name_en,obj.name_zh];
                    attributeSet.keywords = [NSArray arrayWithObjects:obj.name_en,obj.name_zh, nil];
                    
                    if (obj.thumb) {
                        attributeSet.thumbnailURL = [NSURL fileURLWithPath:[DataProcessing fullBookCoverImageUrl:obj.thumb]];
                    }
                    
                    CSSearchableItem *searchableItem = [[CSSearchableItem alloc] initWithUniqueIdentifier:[NSString stringWithFormat:@"%@",@(obj.bookId)]
                                                                                         domainIdentifier:@"books.wawayaya.com"
                                                                                             attributeSet:attributeSet];
                    
                    [itemsToIndex addObject:searchableItem];
                }
                if(itemsToIndex.count > 0)[[CSSearchableIndex defaultSearchableIndex] indexSearchableItems:itemsToIndex
                                                                                         completionHandler:nil];//加
            }];
        }
    } complete:^{
        if(comp)comp();
        //Spotlight 系统搜索，添加
        if (self.isSpotlightClear && ![DataProcessing iOS9_low]) {
            self.isSpotlightClear = NO;
            [self readerDB:^(JRFMDatabase * db) {
                NSArray* tbbooks = [self getList_fromTableClass:tableClass where:@"" db:db];
                NSMutableArray *itemsToIndex = [NSMutableArray array];
                [tbbooks enumerateObjectsUsingBlock:^(TABLE_BOOKS*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    CSSearchableItemAttributeSet *attributeSet = [[CSSearchableItemAttributeSet alloc] initWithItemContentType:(NSString*)kUTTypeJSON];
                    attributeSet.title = obj.name_zh;
                    attributeSet.contentDescription = [NSString stringWithFormat:@"%@/%@【让孩子爱上阅读】",obj.name_en,obj.name_zh];
                    attributeSet.keywords = [NSArray arrayWithObjects:obj.name_en,obj.name_zh, nil];
                    
                    if (obj.thumb) {
                        attributeSet.thumbnailURL = [NSURL fileURLWithPath:[DataProcessing fullBookCoverImageUrl:obj.thumb]];
                    }
                    
                    CSSearchableItem *searchableItem = [[CSSearchableItem alloc] initWithUniqueIdentifier:[NSString stringWithFormat:@"%@",@(obj.bookId)]
                                                                                         domainIdentifier:@"books.wawayaya.com"
                                                                                             attributeSet:attributeSet];
                    
                    [itemsToIndex addObject:searchableItem];
                }];
                [[CSSearchableIndex defaultSearchableIndex] indexSearchableItems:itemsToIndex
                                                               completionHandler:nil];
            }];
        }
    }];
}

#pragma mark-Notice
- (void)getNetNotice_complete:(void (^)(NSDictionary *))comp
{
    NSString* table = [TABLE_NOTICE tableName];
    NSString* tableClass = NSStringFromClass([TABLE_NOTICE class]);
    //
    [self todoForTableName:table tableClass:tableClass netPort:__Ser3_GetNoticeList ref:nil willDB:nil complete:^{
        [self selectNotice:^(NSDictionary *dict) {
            if(comp)comp(dict);
        }];
    }];
}

#pragma mark-Quiz
- (void)getNetQuiz_complete:(void (^)(void))comp
{
    NSString* table = [TABLE_QUIZ tableName];
    NSString* tableClass = NSStringFromClass([TABLE_QUIZ class]);
    //
    [self todoForTableName:table tableClass:tableClass netPort:__Ser2_GetQuizList ref:nil willDB:nil complete:^{
        if(comp)comp();
    }];
}

#pragma mark-SupportFiles
- (void)getNetSupportFiles_complete:(void (^)(NSDictionary *))comp
{
    NSString* table = [TABLE_SUPPORT_FILE tableName];
    NSString* tableClass = NSStringFromClass([TABLE_SUPPORT_FILE class]);
    //
    [self todoForTableName:table tableClass:tableClass netPort:__Ser3_GetSupportFileList ref:nil willDB:nil complete:^{
        [self selectSupportFiles:^(NSDictionary *dict) {
            if(comp)comp(dict);
        }];
    }];
}

#pragma mark- Talk
- (void)getNetTalkList_complete:(void (^)(void))comp
{
    NSString* table = [TABLE_TALK_LIST tableName];
    NSString* tableClass = NSStringFromClass([TABLE_TALK_LIST class]);
    //
    [self todoForTableName:table tableClass:tableClass netPort:__Ser3_GetTalkList ref:nil willDB:nil complete:comp];
}

- (void)getNetTalkVideoList_complete:(void (^)(void))comp
{
    NSString* table = [TABLE_TALK_VEDIO_LIST tableName];
    NSString* tableClass = NSStringFromClass([TABLE_TALK_VEDIO_LIST class]);
    //
    [self todoForTableName:table tableClass:tableClass netPort:__Ser3_GetTalkVideoList ref:nil willDB:^(NSDictionary *retDict) {
        NSArray* dictList = retDict[@"delete"];
        NSMutableArray* deleteArr = [NSMutableArray new];
        for (NSDictionary* dic in dictList) {
            TABLE_TALK_VEDIO_LIST* obj = [TABLE_TALK_VEDIO_LIST JRMJ_objectWithKeyValues:dic];
            long long editon = [[CacheData shareSingle] getEditionFordownloadingTalkVideo:obj.videoId];
            if (obj.edition != editon) {
                [deleteArr addObject:@(obj.videoId)];
                NSString* file = obj.videoUrl;
                if (file) {
                    file = file.lastPathComponent;
                    [DataProcessing deleteTalkVideoFiles:file];
                }
            }
        }
        [[CacheData shareSingle] deleteTalkVideoCacheByIDArray:deleteArr];
        //
    } complete:comp];
}


#pragma mark- 
#pragma mark- private
- (void)todoForTableName:(NSString*)table tableClass:(NSString*)tableClass netPort:(NSString*)port ref:(NSDictionary*)ref willDB:(void (^)(NSDictionary* retDict))netSuccess complete:(void (^)(void))comp
{
    //
    [self isTimestampOut_TABLE_TIMESTAMP_forTable:table complete:^(BOOL isouttime,NSTimeInterval tt) {
        if(!isouttime){
                if(comp)comp();
        }else{
            //
            NSTimeInterval time = tt;
            //debug
            //time = 0;
            UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
            NSMutableDictionary* mdict = [NSMutableDictionary dictionaryWithDictionary:ref];
            [mdict setObject:@(time) forKey:@"data_timestamp"];
            [mdict setObject:@(time) forKey:@"dataTimestamp"];
            NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
            NSString * appVer = [infoDic objectForKey:@"CFBundleVersion"];
            [mdict setObject:appVer forKey:@"appVer"];
            if (uinfo.country_code) {
                [mdict setObject:uinfo.country_code forKey:@"countryCode"];
            }
            [mdict setObject:@"2209410" forKey:@"appId"];
            [self askSer_DB_Net:port parameters:mdict success:^(NSDictionary *retDict) {
                //
                //NSLog(@"--update retDict--%@",retDict);
                if(netSuccess)netSuccess(retDict);
                //
                [DataProcessing do_Async_quick:^{
                    [self.dbQue inTransaction:^(JRFMDatabase *db, BOOL *rollback) {
                        [self deletListToTableClass:tableClass dictArr:retDict[@"delete"] db:db];
                        [self replaceListToTableClass:tableClass dictArr:retDict[@"update"] db:db];
                        NSString* server_timestamp = retDict[@"server_timestamp"];
                        NSInteger uid = [retDict[@"userId"] integerValue];
                        if(server_timestamp)[self update_TABLE_TIMESTAMP_forTable:table uid:uid timestamp:server_timestamp db:db];
                        //
                        [DataProcessing do_Main_quick:^{
                            if(comp)comp();
                        }];
                        //
                    }];
                }];
                
            } failure:^(NSError *error) {
                    if(comp)comp();
            }];
        }
    }];
}


#pragma mark-
#pragma mark- ReadRecord db
//Send Read_Record
#pragma mark-Read_Record
- (void)sendNetLocalReadRecord_complete:(void (^)(JRFMDatabase * db))comp
{
    void(^toSend_Record_end)(JRFMDatabase *db) = ^(JRFMDatabase *db){
            //
            NSArray* list = [self getDictList_fromTableClass:NSStringFromClass([TABLE_READ_RECORD class]) where:@" limit 20" db:db];
            if (list && list.count >0) {
                NSMutableArray* marr = [NSMutableArray arrayWithArray:list];
                NSData* data = [NSJSONSerialization dataWithJSONObject:marr options:NSJSONWritingPrettyPrinted error:nil];
                if (data) {
                    NSString* jsstr = [[NSString alloc] initWithBytes:data.bytes length:data.length encoding:NSUTF8StringEncoding];
                    NSDictionary* dict = @{@"synJsonArrStr":jsstr};
                    [self askSer_Net:__Ser3_Send_StatisticsInfo parameters:dict success:^(NSDictionary *retDict) {
                        [self deletListToTableClass:NSStringFromClass([TABLE_READ_RECORD class]) dictArr:list db:db];
                        [DataProcessing do_Async:^{
                            [self sendNetLocalReadRecord_complete:comp];
                        } delay:0.5];
                    } failure:^(NSError *error) {
                        if (comp)comp(db);
                    }];
                }else{
                   if (comp)comp(db);
                }
            }else{
                if (comp)comp(db);
            }
    };
    //
    [DataProcessing do_Async_quick:^{
        [self.dbQue_Record inTransaction:^(JRFMDatabase *db, BOOL *rollback) {
            NSInteger count = [db intForQuery:[NSString stringWithFormat:@"select count(*) from %@ ",[TABLE_READ_RECORD tableName]]];
            if (count > 0) {
                toSend_Record_end(db);
            }else{
                if (comp)comp(db);
            }
        }];
    }];
}

#pragma mark-Read_Record_Dict
- (void)sendNetLocalReadRecord_Dict_complete:(void (^)(JRFMDatabase *))comp
{
    void(^toSend_Record_end)(JRFMDatabase *db) = ^(JRFMDatabase *db){
        //
        NSArray* list = [self getDictList_fromTableClass:NSStringFromClass([TABLE_READ_RECORD_DICT class]) where:@" limit 20" db:db];
        NSMutableArray* dellist = [NSMutableArray new];
        if (list && list.count >0) {
            NSMutableArray* marr = [NSMutableArray new];
            for (NSDictionary* dic in list) {
                NSString* key = dic[@"key"];
                NSString* value = dic[@"value"];
                id createtime = dic[@"createtime"];
                id remarks = dic[@"remarks"];
                //
                [marr addObject:@{key:value}];
                [dellist addObject:@{@"remarks":remarks,@"createtime":createtime}];
            }
            NSData* data = [NSJSONSerialization dataWithJSONObject:marr options:NSJSONWritingPrettyPrinted error:nil];
            if (data) {
                NSString* jsstr = [[NSString alloc] initWithBytes:data.bytes length:data.length encoding:NSUTF8StringEncoding];
                NSDictionary* dict = @{@"dataJsonStr":jsstr};
                [self askSer_Net:__Ser3_Send_StatisticsInfo_Dict parameters:dict success:^(NSDictionary *retDict) {
                    [self deletListToTableClass:NSStringFromClass([TABLE_READ_RECORD_DICT class]) dictArr:dellist db:db];
                    [DataProcessing do_Async:^{
                        [self sendNetLocalReadRecord_Dict_complete:comp];
                    } delay:0.5];
                } failure:^(NSError *error) {
                    if (comp)comp(db);
                }];
            }else{
                if (comp)comp(db);
            }
        }else{
            if (comp)comp(db);
        }
    };
    //
    [DataProcessing do_Async_quick:^{
        [self.dbQue_Record inTransaction:^(JRFMDatabase *db, BOOL *rollback) {
            NSInteger count = [db intForQuery:[NSString stringWithFormat:@"select count(*) from %@ ",[TABLE_READ_RECORD_DICT tableName]]];
            if (count > 0) {
                toSend_Record_end(db);
            }else{
                if (comp)comp(db);
            }
        }];
    }];
}

#pragma mark-TalkSendSaveInfo
- (void)sendNetTalkInfo_complete:(void (^)(JRFMDatabase *))comp
{
    void(^toSend_tkvedio)(JRFMDatabase *db) = ^(JRFMDatabase *db){
        //
        NSArray* list = [self getDictList_fromTableClass:NSStringFromClass([TABLE_TALK_SAVE_INFO class]) where:@" limit 1" db:db];
        if (list && list.count >0) {
            NSMutableArray* marr = [NSMutableArray arrayWithArray:list];
            NSDictionary* refDict = [marr firstObject];
            if (refDict) {
                NSDictionary* dict = refDict;
                [self askSer_Net:__Ser3_SaveTalkVideoInfo parameters:dict success:^(NSDictionary *retDict) {
                    [self deletListToTableClass:NSStringFromClass([TABLE_READ_RECORD class]) dictArr:list db:db];
                    [DataProcessing do_Async:^{
                        [self sendNetLocalReadRecord_complete:comp];
                    } delay:0.5];
                } failure:^(NSError *error) {
                    if (comp)comp(db);
                }];
            }else{
                if (comp)comp(db);
            }
        }else{
            if (comp)comp(db);
        }
    };
    [DataProcessing do_Async_quick:^{
        [self.dbQue_Record inTransaction:^(JRFMDatabase *db, BOOL *rollback) {
            NSInteger count = [db intForQuery:[NSString stringWithFormat:@"select count(*) from %@ ",[TABLE_TALK_SAVE_INFO tableName]]];
            if (count > 0) {
                toSend_tkvedio(db);
            }else{
                if (comp)comp(db);
            }
        }];
    }];
}

@end
